package com.cloudpivot.receivales.ding.authlogin.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * 钉钉 小程序 免登录 接口
 */
@Controller
@Slf4j
@RequestMapping("/authLoginService/")
public class AuthLoginController {

    @Autowired
    private DingBasicService dingBasicService;

    /**
     * 免登码验证
     * @param authCode
     */
    @PostMapping("/getDingAuthLogin")
    @ResponseBody
    public JSONObject getAuthLogin(@Param(value="authCode") String authCode) {
        log.info("------->authCode----->{}",authCode);
        if (StringUtils.isBlank(authCode)) {
             return getResult(null, -1,"入参异常");
        }
        JSONObject req = new JSONObject();
        req.put("code", authCode);
        String accessToken=dingBasicService.getToken("dingrobottag");
        String reqUrl = String.format("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=%s",accessToken);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(req.toJSONString(), headers);
        JSONObject ret = restTemplate.postForObject(reqUrl, httpEntity, JSONObject.class);
        log.info("getuserinfo的返回---->{}", JSONObject.toJSONString(ret));
        if (!Objects.isNull(ret)) {
            return getResult(ret.getJSONObject("result"), ret.getInteger("errcode"), ret.getString("errmsg"));
        }
        return getResult(null, -2,"钉钉返回异常");
    }

    private JSONObject getResult(JSONObject data, Integer errcode, String errmsg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errcode", errcode);
        jsonObject.put("result", data);
        jsonObject.put("errmsg", errmsg);
        return jsonObject;
    }



}
